package com.jiong.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiong.common.util.PageResult;
import com.jiong.entity.Playlists;
import com.jiong.entity.Songs;
import com.jiong.mapper.SongsMapper;
import com.jiong.service.IPlaylistsService;
import com.jiong.service.ISongsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiong.vo.SongVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiong
 * @since 2025-01-13
 */
@Service
public class SongsServiceImpl extends ServiceImpl<SongsMapper, Songs> implements ISongsService {

    @Autowired
    private IPlaylistsService playlistsService;
    @Autowired
    private SongsMapper songsMapper;

    @Override
    public PageResult<Songs> findByPage(Integer page, Integer pageSize) {
        Page<Songs> SongPage = this.page(new Page<>(page, pageSize));
        SongPage.getRecords().forEach(snog -> {
            Playlists playlists = playlistsService.getById(snog.getPlaylistId());
            if (playlists != null) {
                snog.setPlaylistName(playlists.getPlaylistName());
            }
        });
        return new PageResult<>(SongPage.getRecords(), SongPage.getTotal());
    }

    @Override
    public PageResult<Songs> search(Integer page, Integer pageSize, SongVO songVO) {
        // 构建查询条件
        QueryWrapper<Songs> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(songVO.getSongName()), "song_name", songVO.getSongName())  // 按歌曲名模糊查询
                .like(StrUtil.isNotBlank(songVO.getArtistName()), "artist_name", songVO.getArtistName())  // 按艺术家模糊查询
                .eq(songVO.getPlaylistId() != null, "playlist_id", songVO.getPlaylistId())  // 按播放列表ID精确查询
                .eq(songVO.getReleasedYear() != null, "released_year", songVO.getReleasedYear());  // 按创建年份精确查询

        // 执行分页查询
        Page<Songs> songsPage = this.page(new Page<>(page, pageSize), queryWrapper);

        // 遍历查询结果，设置播放列表名称
        songsPage.getRecords().forEach(song -> {
            Playlists playlists = playlistsService.getById(song.getPlaylistId());
            if (playlists != null) {
                song.setPlaylistName(playlists.getPlaylistName());
            }
        });

        return new PageResult<>(songsPage.getRecords(), songsPage.getTotal());
    }

    @Override
    public boolean add(Songs songs) {
        return this.save(songs);
    }
}
